<template>
  <div class="checkin-page">
    <h1 class="page-title">
      <el-icon><Star /></el-icon>
      每日打卡
    </h1>

    <!-- 今日打卡区域 -->
    <el-card class="checkin-card mb-20">
      <template #header>
        <div class="card-header">
          <el-icon><Calendar /></el-icon>
          <span>今日打卡</span>
          <span class="today-date">{{ formatDate(new Date()) }}</span>
        </div>
      </template>
      
      <div class="checkin-main">
        <div class="checkin-status">
          <div class="checkin-icon" :class="{ 'checked-in': todayCheckedIn }">
            <el-icon v-if="!todayCheckedIn"><Clock /></el-icon>
            <el-icon v-else><CircleCheck /></el-icon>
          </div>
          <div class="checkin-text">
            <h3 v-if="!todayCheckedIn">今天还没有打卡</h3>
            <h3 v-else>今日已打卡完成！</h3>
            <p v-if="!todayCheckedIn">完成学习任务后记得打卡哦~</p>
            <p v-else>已于 {{ todayCheckInTime }} 完成打卡</p>
          </div>
        </div>

        <!-- 学习内容输入 -->
        <div class="checkin-form" v-if="!todayCheckedIn">
          <el-form ref="checkInFormRef" :model="checkInForm" :rules="checkInRules" label-width="120px">
            <el-form-item label="今日学习内容" prop="content">
              <el-input 
                v-model="checkInForm.content" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入今天的学习内容、学习心得或遇到的问题..."
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="学习时长" prop="duration">
              <el-select v-model="checkInForm.duration" placeholder="请选择学习时长">
                <el-option label="1小时以内" value="1"></el-option>
                <el-option label="1-2小时" value="2"></el-option>
                <el-option label="2-3小时" value="3"></el-option>
                <el-option label="3小时以上" value="4"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="完成度" prop="completeness">
              <el-rate 
                v-model="checkInForm.completeness" 
                :max="5" 
                show-text 
                :texts="['很差', '一般', '良好', '很好', '完美']"
              />
            </el-form-item>
            
            <el-form-item label="心情指数" prop="mood">
              <el-rate 
                v-model="checkInForm.mood" 
                :max="5" 
                show-text 
                :texts="['😞', '😐', '🙂', '😊', '😄']"
                :colors="['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#67C23A']"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitCheckIn" :loading="submitting" size="large">
                <el-icon><CircleCheck /></el-icon>
                完成打卡
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 已打卡状态 -->
        <div class="checked-in-info" v-else>
          <div class="check-in-summary">
            <div class="summary-item">
              <el-icon><Document /></el-icon>
              <div>
                <div class="summary-label">学习内容</div>
                <div class="summary-content">{{ todayCheckIn.content }}</div>
              </div>
            </div>
            <div class="summary-item">
              <el-icon><Timer /></el-icon>
              <div>
                <div class="summary-label">学习时长</div>
                <div class="summary-content">{{ getDurationText(todayCheckIn.duration) }}</div>
              </div>
            </div>
            <div class="summary-item">
              <el-icon><Trophy /></el-icon>
              <div>
                <div class="summary-label">完成度</div>
                <div class="summary-content">
                  <el-rate v-model="todayCheckIn.completeness" disabled />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 打卡统计 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :sm="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon"><Calendar /></el-icon>
            <div>
              <div class="stat-number">{{ checkInStats.totalDays }}</div>
              <div class="stat-label">累计打卡</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon"><Lightning /></el-icon>
            <div>
              <div class="stat-number">{{ checkInStats.currentStreak }}</div>
              <div class="stat-label">连续打卡</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon"><TrendCharts /></el-icon>
            <div>
              <div class="stat-number">{{ checkInStats.avgScore.toFixed(1) }}</div>
              <div class="stat-label">平均完成度</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 打卡日历 -->
    <el-card class="mb-20">
      <template #header>
        <div class="card-header">
          <el-icon><Calendar /></el-icon>
          <span>打卡日历</span>
        </div>
      </template>
      
      <el-calendar v-model="calendarDate" class="check-in-calendar">
        <template #date-cell="{ data }">
          <div class="calendar-cell" :class="getCalendarCellClass(data.day)">
            <div class="calendar-date">{{ data.day.split('-').pop() }}</div>
            <div class="calendar-indicator" v-if="isCheckedInDate(data.day)">
              <el-icon><CircleCheck /></el-icon>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 打卡历史 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>打卡历史</span>
        </div>
      </template>
      
      <div class="checkin-history">
        <el-timeline>
          <el-timeline-item 
            v-for="record in checkInHistory" 
            :key="record.date"
            :timestamp="formatDate(record.date)"
            :color="getTimelineColor(record.completeness)"
          >
            <el-card class="history-card">
              <div class="history-content">
                <div class="history-header">
                  <span class="history-title">第{{ record.day }}天学习</span>
                  <div class="history-meta">
                    <el-tag size="small">{{ getDurationText(record.duration) }}</el-tag>
                    <el-rate v-model="record.completeness" disabled size="small" />
                  </div>
                </div>
                <p class="history-desc">{{ record.content }}</p>
                <div class="history-footer">
                  <span class="history-mood">心情：{{ getMoodEmoji(record.mood) }}</span>
                  <span class="history-time">{{ record.checkInTime }}</span>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <div v-if="checkInHistory.length === 0" class="empty-history">
          <el-empty description="还没有打卡记录，快去完成第一次打卡吧！" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import api from '@/utils/api'

// 表单数据
const checkInForm = ref({
  content: '',
  duration: '',
  completeness: 0,
  mood: 0
})

// 表单验证规则
const checkInRules = ref({
  content: [
    { required: true, message: '请输入今日学习内容', trigger: 'blur' },
    { min: 10, message: '请至少输入10个字符', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请选择学习时长', trigger: 'change' }
  ],
  completeness: [
    { required: true, message: '请为今日学习完成度评分', trigger: 'change' }
  ],
  mood: [
    { required: true, message: '请选择心情指数', trigger: 'change' }
  ]
})

// 其他状态
const checkInFormRef = ref()
const submitting = ref(false)
const calendarDate = ref(new Date())

// 今日打卡状态
const todayCheckedIn = ref(false)
const todayCheckInTime = ref('')
const todayCheckIn = ref({})

// 打卡统计
const checkInStats = ref({
  totalDays: 3,
  currentStreak: 2,
  avgScore: 4.2
})

// 打卡历史记录
const checkInHistory = ref([
  {
    date: '2024-01-15',
    day: 3,
    content: '今天学习了CSS基础，包括选择器、颜色、字体设置等。练习了几个小案例，对CSS的理解更深入了。',
    duration: '3',
    completeness: 4,
    mood: 4,
    checkInTime: '21:30'
  },
  {
    date: '2024-01-14',
    day: 2,
    content: '学习了HTML表单元素，包括input、select、textarea等。完成了注册表单的作业。',
    duration: '2',
    completeness: 5,
    mood: 5,
    checkInTime: '20:15'
  },
  {
    date: '2024-01-13',
    day: 1,
    content: '开始学习HTML基础，了解了基本标签结构，创建了第一个网页。很兴奋！',
    duration: '2',
    completeness: 4,
    mood: 5,
    checkInTime: '19:45'
  }
])

// 检查今日是否已打卡
const checkTodayStatus = () => {
  const today = formatDate(new Date())
  const todayRecord = checkInHistory.value.find(record => record.date === today)
  
  if (todayRecord) {
    todayCheckedIn.value = true
    todayCheckInTime.value = todayRecord.checkInTime
    todayCheckIn.value = todayRecord
  }
}

// 提交打卡
const submitCheckIn = async () => {
  try {
    await checkInFormRef.value.validate()
    
    submitting.value = true
    
    const now = new Date()
    
    // 调用后端API保存打卡数据
    const response = await api.post('/checkin', {
      checkin_date: formatDate(now),
      study_content: checkInForm.value.content,
      study_hours: parseInt(checkInForm.value.duration),
      completion_rate: checkInForm.value.completeness,
      mood_rating: checkInForm.value.mood,
      notes: ''
    })
    
    if (response.data.success !== false) {
      const newCheckIn = {
        date: formatDate(now),
        day: checkInHistory.value.length + 1,
        content: checkInForm.value.content,
        duration: checkInForm.value.duration,
        completeness: checkInForm.value.completeness,
        mood: checkInForm.value.mood,
        checkInTime: now.toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5)
      }
      
      // 添加到历史记录
      checkInHistory.value.unshift(newCheckIn)
      
      // 更新今日状态
      todayCheckedIn.value = true
      todayCheckInTime.value = newCheckIn.checkInTime
      todayCheckIn.value = newCheckIn
      
      // 更新统计
      updateStats()
      
      // 同时保存到本地存储作为备份
      saveCheckInData()
      
      ElMessage.success('打卡成功！数据已保存到服务器')
      
      // 重置表单
      checkInFormRef.value.resetFields()
    }
    
  } catch (error) {
    console.error('打卡失败:', error)
    ElMessage.error('打卡失败，请检查网络连接')
    
    // 如果API失败，仍然保存到本地
    const now = new Date()
    const newCheckIn = {
      date: formatDate(now),
      day: checkInHistory.value.length + 1,
      content: checkInForm.value.content,
      duration: checkInForm.value.duration,
      completeness: checkInForm.value.completeness,
      mood: checkInForm.value.mood,
      checkInTime: now.toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5)
    }
    
    checkInHistory.value.unshift(newCheckIn)
    todayCheckedIn.value = true
    todayCheckInTime.value = newCheckIn.checkInTime
    todayCheckIn.value = newCheckIn
    updateStats()
    saveCheckInData()
    
    ElMessage.warning('打卡数据已保存到本地，请稍后同步到服务器')
  } finally {
    submitting.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  checkInStats.value.totalDays = checkInHistory.value.length
  
  // 计算连续打卡天数
  let streak = 0
  const today = new Date()
  for (let i = 0; i < checkInHistory.value.length; i++) {
    const recordDate = new Date(checkInHistory.value[i].date)
    const diffDays = Math.floor((today - recordDate) / (1000 * 60 * 60 * 24))
    
    if (diffDays === i) {
      streak++
    } else {
      break
    }
  }
  checkInStats.value.currentStreak = streak
  
  // 计算平均完成度
  const totalScore = checkInHistory.value.reduce((sum, record) => sum + record.completeness, 0)
  checkInStats.value.avgScore = totalScore / checkInHistory.value.length
}

// 格式化日期
const formatDate = (date) => {
  // 如果已经是字符串格式（YYYY-MM-DD），直接返回
  if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
    return date
  }
  
  // 如果是Date对象，转换为ISO字符串
  if (date instanceof Date) {
    return date.toISOString().split('T')[0]
  }
  
  // 尝试将字符串转换为Date对象再格式化
  if (typeof date === 'string') {
    const dateObj = new Date(date)
    if (!isNaN(dateObj.getTime())) {
      return dateObj.toISOString().split('T')[0]
    }
  }
  
  // 如果都失败了，返回当前日期
  return new Date().toISOString().split('T')[0]
}

// 获取学习时长文本
const getDurationText = (duration) => {
  const durationMap = {
    '1': '1小时以内',
    '2': '1-2小时',
    '3': '2-3小时',
    '4': '3小时以上'
  }
  return durationMap[duration] || '未知'
}

// 获取心情表情
const getMoodEmoji = (mood) => {
  const moodMap = {
    1: '😞',
    2: '😐',
    3: '🙂',
    4: '😊',
    5: '😄'
  }
  return moodMap[mood] || '🙂'
}

// 检查某日期是否已打卡
const isCheckedInDate = (dateStr) => {
  return checkInHistory.value.some(record => record.date === dateStr)
}

// 获取日历单元格样式
const getCalendarCellClass = (dateStr) => {
  const today = formatDate(new Date())
  const isToday = dateStr === today
  const isCheckedIn = isCheckedInDate(dateStr)
  
  return {
    'is-today': isToday,
    'is-checked-in': isCheckedIn
  }
}

// 获取时间线颜色
const getTimelineColor = (completeness) => {
  if (completeness >= 4) return '#67c23a'
  if (completeness >= 3) return '#409eff'
  if (completeness >= 2) return '#e6a23c'
  return '#f56c6c'
}

// 保存打卡数据
const saveCheckInData = () => {
  localStorage.setItem('checkInData', JSON.stringify({
    history: checkInHistory.value,
    stats: checkInStats.value
  }))
}

// 从服务器加载打卡数据
const loadCheckInDataFromServer = async () => {
  try {
    const response = await api.get('/checkin/history')
    
    if (response.data && response.data.checkins) {
      const serverCheckins = response.data.checkins
      
      // 将服务器数据转换为前端格式
      checkInHistory.value = serverCheckins.map((checkin, index) => ({
        date: checkin.checkin_date,
        day: index + 1,
        content: checkin.study_content,
        duration: checkin.study_hours.toString(),
        completeness: checkin.completion_rate,
        mood: checkin.mood_rating,
        checkInTime: new Date(checkin.created_at).toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5)
      }))
      
      // 更新统计数据
      if (response.data.stats) {
        checkInStats.value = {
          totalDays: response.data.stats.totalCheckins || checkInHistory.value.length,
          currentStreak: response.data.stats.currentStreak || 0,
          avgScore: response.data.stats.averageCompletion || 0
        }
      }
      
      ElMessage.success('已从服务器加载打卡数据')
      return true
    }
  } catch (error) {
    console.error('从服务器加载打卡数据失败:', error)
    ElMessage.warning('无法从服务器加载打卡数据，使用本地数据')
    return false
  }
}

// 从本地存储加载打卡数据（备用方案）
const loadCheckInDataFromLocal = () => {
  const saved = localStorage.getItem('checkInData')
  if (saved) {
    const data = JSON.parse(saved)
    checkInHistory.value = data.history || []
    checkInStats.value = data.stats || checkInStats.value
    ElMessage.info('已加载本地缓存的打卡数据')
  }
}

// 组件挂载时初始化
onMounted(async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载打卡数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    // 优先从服务器加载，失败则从本地加载
    const serverLoaded = await loadCheckInDataFromServer()
    
    if (!serverLoaded) {
      loadCheckInDataFromLocal()
    }
    
    checkTodayStatus()
    updateStats()
  } finally {
    loading.close()
  }
})
</script>

<style scoped>
.checkin-page {
  padding: 0;
}

/* 通用样式类 */
.mb-10 {
  margin-bottom: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

.page-title .el-icon {
  margin-right: 12px;
  color: #409eff;
  font-size: 28px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

/* 打卡卡片 */
.checkin-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  overflow: hidden;
}

.checkin-card :deep(.el-card__header) {
  background: transparent;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.checkin-card .card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
}

.today-date {
  font-size: 14px;
  opacity: 0.8;
}

.checkin-main {
  padding: 20px 0;
}

.checkin-status {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.checkin-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  border: 2px dashed rgba(255, 255, 255, 0.3);
  transition: all 0.3s;
}

.checkin-icon.checked-in {
  background: rgba(103, 194, 58, 0.2);
  border-color: #67c23a;
  color: #67c23a;
}

.checkin-icon .el-icon {
  font-size: 32px;
}

.checkin-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.checkin-text p {
  margin: 0;
  opacity: 0.8;
}

/* 表单样式 */
.checkin-form {
  background: rgba(255, 255, 255, 0.1);
  padding: 30px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.checkin-form :deep(.el-form-item__label) {
  color: white;
}

.checkin-form :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
}

.checkin-form :deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.9);
}

/* 已打卡信息 */
.checked-in-info {
  background: rgba(255, 255, 255, 0.1);
  padding: 30px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.check-in-summary {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.summary-item .el-icon {
  font-size: 18px;
  margin-top: 2px;
  opacity: 0.8;
}

.summary-label {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.summary-content {
  font-size: 14px;
  line-height: 1.5;
}

/* 统计卡片 */
.stat-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 12px;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
  text-align: center;
}

.stat-icon {
  font-size: 32px;
  color: #409eff;
  margin-right: 15px;
  flex-shrink: 0;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 6px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

/* 日历样式 */
.check-in-calendar :deep(.el-calendar-table) {
  border: none;
}

.calendar-cell {
  position: relative;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  transition: all 0.3s;
}

.calendar-cell.is-today {
  background: #409eff;
  color: white;
}

.calendar-cell.is-checked-in {
  background: #f0f9ff;
  color: #409eff;
}

.calendar-cell.is-today.is-checked-in {
  background: #67c23a;
  color: white;
}

.calendar-date {
  font-size: 16px;
  font-weight: 500;
}

.calendar-indicator {
  position: absolute;
  bottom: 4px;
  right: 4px;
  font-size: 12px;
  color: #67c23a;
}

/* 历史记录 */
.checkin-history {
  padding: 10px 0;
}

.history-card {
  margin-bottom: 0;
  box-shadow: none;
  border: 1px solid #f0f0f0;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.history-title {
  font-weight: 500;
  color: #303133;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.history-desc {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.6;
}

.history-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.empty-history {
  text-align: center;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stat-content {
    padding: 15px;
  }
  
  .stat-icon {
    font-size: 28px;
    margin-right: 12px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .page-title .el-icon {
    font-size: 24px;
  }
  
  .stat-card {
    height: 100px;
    margin-bottom: 12px;
  }
  
  .stat-content {
    padding: 12px;
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 8px;
    font-size: 24px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .checkin-status {
    flex-direction: column;
    text-align: center;
  }
  
  .check-in-summary {
    gap: 16px;
  }
  
  .history-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .history-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .checkin-page {
    padding: 0 10px;
  }
  
  .stat-card {
    height: 90px;
  }
  
  .stat-content {
    padding: 10px;
  }
  
  .stat-number {
    font-size: 18px;
  }
  
  .stat-label {
    font-size: 12px;
  }
}
</style> 